﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using RestSharp;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using JsonException = Newtonsoft.Json.JsonException;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "sap")]
    public class SapService : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<SapService> _logger = null;
        public SapService() : base(YdConstants.YIDEA, "Sap", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<SapService>>();
        }
        public override void ExecuteCore()
        {
            AssetSyncEvent Data = (AssetSyncEvent)State!;
            _logger.LogInformation("推sap进来了:" + Data.SourceType);
            //资产
            if ((Data.SourceType == 0 || Data.SourceType == 11) && Data.EventType == EventType.Created)
            {
                var assetTypeCode = Data.Data!["AssetTypeCode"].ToString();
                var invoiceCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
                var IsPosted = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");


                if (IsPush(assetTypeCode) && (Data.Data![invoiceCodeField.FieldId] == null || Data.Data![invoiceCodeField.FieldId].ToString() == "0"))
                {
                    _logger.LogInformation("可以推送sap资产啦：" + Data.Data!["Barcode"]!.ToString());
                    Asset asset = new Asset();
                    asset.Barcode = Data.Data!["Barcode"]!.ToString();
                    var companyCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                    var companyCodeValue = Data!.Data?[companyCodeField.FieldId]?.ToString();
                    asset.OwnCompanyCode = companyCodeValue;
                    asset.AssetTypeCode = GetTopAssetTypeCode(Data!.Data?["AssetTypeCode"]?.ToString());
                    asset.Name = Data.Data!["Name"]?.ToString();
                    if (Data.Data!["Specs"] == null)
                    {
                        asset.Specs = "";
                    }
                    else
                    {
                        asset.Specs = Data.Data!["Specs"]!.ToString();
                    }
                    var measureUnit = Data.Data!["MeasureUnit"];
                    if (measureUnit == null)
                    {
                        measureUnit = "";
                    }
                    asset.MeasureUnit = measureUnit.ToString();
                    var centerCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");
                    var centerCodeValue = Data!.Data?[centerCodeField.FieldId]?.ToString();
                    asset.UseCompanyCode = centerCodeValue;

                    var ComputerName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "计算机名");
                    var IsGuoZhangName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");
                    var AssetTypeCode = Data.Data!["AssetTypeCode"].ToString();
                    if (AssetTypeCode == "GE01" || AssetTypeCode == "LE01" || AssetTypeCode == "LE02" || AssetTypeCode == "GE02" || AssetTypeCode == "LE14" || AssetTypeCode == "GE14" || AssetTypeCode == "LE29" || AssetTypeCode == "GE29")
                    {
                        var AssetCode = Data.Data!["Barcode"]!.ToString();
                        var AssetDate = YideaClient.GetAsset(AssetCode);
                        var DataJson = AssetDate.DataJson;
                        var JieXiDataJson = JObject.Parse(DataJson);
                        JieXiDataJson[ComputerName.FieldId] = AssetCode;
                        JieXiDataJson[IsGuoZhangName.FieldId] = "否";
                        AssetDate.DataJson = JieXiDataJson.ToString();
                        var ShiFou = YideaClient.UpdateAsset(AssetDate, AssetDate);
                        if (ShiFou == true)
                        {
                            _logger.LogInformation("修改成功");
                        }
                    }
                    else
                    {
                        var AssetCode = Data.Data!["Barcode"]!.ToString();
                        var AssetDate = YideaClient.GetAsset(AssetCode);
                        var DataJson = AssetDate.DataJson;
                        var JieXiDataJson = JObject.Parse(DataJson);
                        JieXiDataJson[IsGuoZhangName.FieldId] = "否";
                        AssetDate.DataJson = JieXiDataJson.ToString();
                        var ShiFou = YideaClient.UpdateAsset(AssetDate, AssetDate);
                        if (ShiFou == true)
                        {
                            _logger.LogInformation("修改成功");
                        }
                    }


                    ToClient.AddNewAsset(asset);
                }
                else
                {
                    var ComputerName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "计算机名");
                    var IsGuoZhangName = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");
                    var PurchaseNoField = ExtendFields.First(x => x.ObjectType == 57 && x.Name == "入库单收货单号");

                    var AssetTypeCode = Data.Data!["AssetTypeCode"].ToString();
                    var getInStorages = YideaClient.GetAssetInStorages(new QueryParam() { FilterString = "extensionFilters=[{label:\"serialNo\",operator:\"EqualTo\",value:\"" + Data.Data!["PurchaseReceiveSerialNo"].ToString() + "\"}]" }).FirstOrDefault();
                    var Purchaseobj = System.Text.Json.JsonSerializer.Deserialize<JsonObject>(getInStorages.ExtraData["dataJson"].ToString());
                    //收货单流水号
                    var PurchSerialNo = Purchaseobj[PurchaseNoField.FieldId].ToString();
                    var AssetCode = Data.Data!["Barcode"]!.ToString();
                    var AssetDate = YideaClient.GetAsset(AssetCode);
                    var DataJson = AssetDate.DataJson;
                    var JieXiDataJson = JObject.Parse(DataJson);
                    string AssetSource = string.Empty;
                    AssetSource = PurchSerialNo.Substring(0, 4);
                    if (AssetSource.Contains("ZERO"))
                    {
                        JieXiDataJson[IsGuoZhangName.FieldId] = "是";
                    }
                    else
                    {
                        JieXiDataJson[IsGuoZhangName.FieldId] = "否";
                    }
                    if (AssetTypeCode == "GE01" || AssetTypeCode == "LE01" || AssetTypeCode == "LE02" || AssetTypeCode == "GE02" || AssetTypeCode == "LE14" || AssetTypeCode == "GE14" || AssetTypeCode == "LE29" || AssetTypeCode == "GE29")
                    {
                        JieXiDataJson[ComputerName.FieldId] = AssetCode;
                        AssetDate.DataJson = JieXiDataJson.ToString();
                        var ShiFou = YideaClient.UpdateAsset(AssetDate, AssetDate);
                        if (ShiFou == true)
                        {
                            _logger.LogInformation("修改成功");
                        }
                    }
                    else
                    {
                        AssetDate.DataJson = JieXiDataJson.ToString();
                        var ShiFou = YideaClient.UpdateAsset(AssetDate, AssetDate);
                        if (ShiFou == true)
                        {
                            _logger.LogInformation("修改成功");
                        }
                    }

                }
            }
            if (Data.EventType == EventType.ReceiptEffect)
            {
                var serialNo = Data!.Data!["SerialNo"]!.ToString();
                string code = serialNo.Substring(0, 3);

                switch (code)
                {
                    //报废
                    case "CLN":
                        AssetClear assetClear = new AssetClear();

                        var memoField = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "清理说明");
                        var memoBFType = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "报废类型");
                        var formId = UserDefines.First(x => x.Name == "报废自定义表单");
                        var assetField = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "资产列表");
                        string Bftype = Data.Data[memoBFType.FieldId]?.ToString();

                        string firstPart = string.Empty;
                        string secondPart = string.Empty;

                        if (!string.IsNullOrEmpty(Bftype))
                        {
                            JsonDocument doc;
                            try
                            {
                                doc = JsonDocument.Parse(Bftype);
                                string value = doc.RootElement.GetProperty("value").GetString();
                                if (!string.IsNullOrEmpty(value))
                                {
                                    string[] parts = value.Split('-');
                                    firstPart = parts.Length > 0 ? parts[0] : string.Empty;
                                    secondPart = parts.Length > 1 ? parts[1].Trim() : string.Empty;
                                }
                            }
                            catch (JsonException ex)
                            { }
                        }

                        assetClear.ExtraData = new JsonObject
                        {
                            ["SerialNo"] = Data.Data["SerialNo"]!.ToString(),
                            ["Memo"] = Data.Data[memoField.FieldId]?.ToString(),

                            ["ZBFLX"] = firstPart,
                            ["ZBFLXTXT"] = secondPart
                        };
                        assetClear.AssetList = GetPushAssets(Data, 48);
                        if (assetClear.AssetList.Count > 0)
                        {
                            var flag = ToClient.AddAssetClear(assetClear);
                            var SapStatus = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "sap单据状态");
                            UserDefine clearDefine = UserDefines.First(x => x.Name == "报废自定义表单");
                            var condition = new JsonArray();
                            condition.Add(new JsonObject()
                            {
                                ["field"] = "serialNo",
                                ["type"] = "input",
                                ["label"] = "流水号",
                                ["opt"] = "Equal",
                                ["val"] = serialNo
                            });
                            CustomizedFormData order = YideaClient.GetCustomizedFormDatas(clearDefine.Id, new QueryParam() { FilterString = System.Text.Json.JsonSerializer.Serialize(condition) }).FirstOrDefault();
                            var dataJson = JsonNode.Parse(order.Data["dataJson"].ToString());
                            string message = string.Empty;
                            if (flag)
                            {
                                message = "SAP 已接收请求，待处理";
                                dataJson[SapStatus.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = clearDefine.Id, JsonData = System.Text.Json.JsonSerializer.Serialize(dataJson) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                _logger.LogInformation("修改结果" + updateResponse);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"资产报废单SerialNo：【{serialNo}】已成功发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】,修改SAP状态时,调用易点易动接口失败");
                                }

                            }
                            else
                            {
                                message = "SAP 未收到请求，请咨询客服处理";
                                dataJson[SapStatus.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = clearDefine.Id, JsonData = System.Text.Json.JsonSerializer.Serialize(dataJson) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                _logger.LogInformation("修改结果" + updateResponse);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"资产报废单SerialNo：【{serialNo}】未发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"调拨单SerialNo：【{serialNo}】未发送至SAP,修改SAP状态时,调用易点易动接口失败");
                                }
                            }

                        }
                        break;
                    //发票登记单
                    case "IEF":
                        CustomizedFormData customizedFormData = new CustomizedFormData();
                        var companyCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "公司代码");
                        var currencyCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "货币");
                        var employeeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "员工编号");
                        var invoiceCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票代码");
                        var invoiceNumField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票号码");
                        var vendorField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "供应商");
                        var BuDateField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "过账日期");
                        JsonArray jsonArray = new JsonArray();
                        var assets = GetPushAssets(Data, 50);
                        foreach (var asset in assets)
                        {
                            var facode = asset.ExtraData["FACode"].ToString();
                            var taxAmount = asset.ExtraData["TaxAmount"].ToString();
                            var totalPriceAndTax = asset.ExtraData["TotalPriceAndTax"].ToString();
                            var centerCode = asset.ExtraData["CenterCode"].ToString();
                            JsonObject model = new JsonObject();
                            model.Add("Barcode", asset.Barcode);
                            model.Add("FACode", facode);
                            model.Add("Name", asset.Name);
                            model.Add("Amount", asset.Amount);
                            model.Add("TaxAmount", taxAmount);
                            model.Add("TotalPriceAndTax", totalPriceAndTax);
                            model.Add("AssetTypeCode", asset.AssetTypeCode);
                            model.Add("CenterCode", centerCode);
                            model.Add("InvoiceTypeCode", asset.ExtraData["InvoiceTypeCode"].ToString());
                            model.Add("TaxCode", asset.ExtraData["TaxCode"].ToString());

                            jsonArray.Add(model);
                        }
                        var invoiceListCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票列表");
                        var invoiceList = Data.Data![invoiceListCodeField.FieldId].AsArray();
                        JsonArray invoiveAarry = new JsonArray();
                        foreach (var invoice in invoiceList)
                        {
                            JsonObject model = new JsonObject
                            {
                                ["InvoiceCode"] = invoice[invoiceCodeField.FieldId]!.ToString(),
                                ["InvoiceNum"] = invoice[invoiceNumField.FieldId]!.ToString(),

                            };
                            invoiveAarry.Add(model);
                        }

                        customizedFormData.Data = new JsonObject
                        {
                            ["CompanyCode"] = Data.Data[companyCodeField.FieldId]?.ToString(),
                            ["Currency"] = Data.Data[currencyCodeField.FieldId]?.ToString(),
                            ["EmployeeNo"] = Data.Data[employeeField.FieldId]?.ToString(),
                            ["Vendor"] = Data.Data[vendorField.FieldId]?.ToString(),
                            ["SerialNo"] = Data.Data["SerialNo"]?.ToString(),
                            ["Assets"] = jsonArray,
                            ["Invoices"] = invoiveAarry,
                            ["BuDateField"] = Data.Data[BuDateField.FieldId]?.ToString()
                        };
                        if (assets.Count > 0)
                        {
                            var flag = ToClient.AddNewCustomizedFormData(customizedFormData);
                            UserDefine userDefine = UserDefines.First(x => x.Name == "发票登记自定义表单");
                            var sapStatus = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "sap单据状态");
                            var condition = new JsonArray();
                            condition.Add(new JsonObject()
                            {
                                ["field"] = "serialNo",
                                ["type"] = "input",
                                ["label"] = "流水号",
                                ["opt"] = "Equal",
                                ["val"] = serialNo
                            });
                            CustomizedFormData order = new CustomizedFormData();
                            order = YideaClient.GetCustomizedFormDatas(userDefine.Id, new QueryParam() { FilterString = System.Text.Json.JsonSerializer.Serialize(condition) }).FirstOrDefault();
                            var jsondata = System.Text.Json.JsonSerializer.Deserialize<JsonObject>(order.Data["dataJson"].ToString());
                            string message = string.Empty;
                            if (flag)
                            {
                                message = "SAP 已接收请求，待处理";
                                jsondata[sapStatus.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = userDefine.Id, JsonData = System.Text.Json.JsonSerializer.Serialize(jsondata) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                _logger.LogInformation("修改结果" + updateResponse);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"发票登记单SerialNo：【{serialNo}】已成功发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"发票登记单SerialNo：【{serialNo}】,修改SAP状态时,调用易点易动接口失败");
                                }
                            }
                            else
                            {
                                message = "SAP 未收到请求，请咨询客服处理";
                                jsondata[sapStatus.FieldId] = message;
                                UserDefinedForm userDefinedForm = new UserDefinedForm() { Id = order.Id, SerialNo = serialNo, FormId = userDefine.Id, JsonData = System.Text.Json.JsonSerializer.Serialize(jsondata) };
                                var updateResponse = YideaClient.UpdateUserDefinedForm(userDefinedForm, null);
                                _logger.LogInformation("修改结果" + updateResponse);
                                if (updateResponse)
                                {
                                    _logger.LogInformation($"发票登记单SerialNo：【{serialNo}】未发送至SAP，当前SAP推送状态修改为：{message}");
                                }
                                else
                                {
                                    _logger.LogInformation($"发票登记单SerialNo：【{serialNo}】未发送至SAP,修改SAP状态时,调用易点易动接口失败");
                                }
                            }


                        }
                        break;
                    //盘点单
                    default:
                        break;
                }
            }
        }


        private List<Asset> GetPushAssets(AssetSyncEvent Data, int sourceType)
        {
            //int sourceType = Data.SourceType;
            var assetField = ExtendFields.First(x => x.ObjectType == sourceType && x.Name == "资产列表");
            var assetQueryField = ExtendFields.First(x => x.ObjectType == sourceType && x.Name == "资产列表query");
            var list = Data.Data![assetField.FieldId].AsArray();
            var pushAssets = new List<Asset>();
            foreach (var item in list)
            {
                var barcode = item["barcode"] == null ? item[assetQueryField.FieldId]["barcode"]?.ToString() : item["barcode"]?.ToString();
                var assetTypeCode = "";
                if (item["assetTypeCode"] == null)
                {
                    if (item[assetQueryField.FieldId]["assetTypeCode"] == null)
                    {
                        var asset = YideaClient.GetAsset(barcode);
                        if (asset != null)
                        {
                            assetTypeCode = asset.AssetTypeCode;
                        }

                    }
                    else
                    {
                        assetTypeCode = item[assetQueryField.FieldId]["assetTypeCode"].ToString();
                    }
                }
                else
                {
                    assetTypeCode = item["assetTypeCode"].ToString();
                }
                if (sourceType == 50 || IsPush(assetTypeCode))
                {

                    var facodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                    var centerField = ExtendFields.First(x => x.ObjectType == 49 && x.Name == "调入成本中心码");
                    var companyCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                    var amountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "不含税金额");
                    var taxAmountField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税额");
                    var totalPriceAndTaxField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "价税合计");
                    var invoiceTypeCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "发票类型代码");
                    var taxCodeField = ExtendFields.First(x => x.ObjectType == 50 && x.Name == "税码");
                    var assetCenterCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");
                    var clearCompanyCode = ExtendFields.First(x => x.ObjectType == 48 && x.Name == "公司代码");

                    var amount = 0.0M;
                    if (sourceType == 50)
                    {
                        var assetAmount = item[amountField.FieldId] == null ? item[assetQueryField.FieldId][amountField.FieldId]?.ToString() : item[amountField.FieldId]?.ToString();
                        decimal.TryParse(assetAmount, out amount);
                    }
                    var FACode = "";

                    if (item[facodeField.FieldId] != null || item[assetQueryField.FieldId][facodeField.FieldId] != null)
                    {
                        FACode = item[facodeField.FieldId] == null ? item[assetQueryField.FieldId][facodeField.FieldId]?.ToString() : item[facodeField.FieldId]?.ToString();

                    }
                    //if (string.IsNullOrEmpty(FACode))
                    //{
                    //    continue;
                    //}
                    string spec = "";
                    if (item["specs"] != null || item[assetQueryField.FieldId]["specs"] != null)
                    {
                        spec = item["specs"] == null ? item[assetQueryField.FieldId]["specs"]?.ToString() : item["specs"]?.ToString();
                    }

                    var centercode = "";
                    if (item[assetCenterCodeField.FieldId] == null && item[assetQueryField.FieldId][assetCenterCodeField.FieldId] == null)
                    {
                        if (item["dataJson"] != null || item[assetQueryField.FieldId]["dataJson"] != null)
                        {
                            var assetDataJson = item["dataJson"] == null ? item[assetQueryField.FieldId]["dataJson"]?.ToString() : item["dataJson"]?.ToString();
                            var datajson = JsonNode.Parse(assetDataJson).AsObject();
                            centercode = datajson[assetCenterCodeField.FieldId]?.ToString();
                        }
                    }
                    else
                    {
                        centercode = item[assetCenterCodeField.FieldId] == null ? item[assetQueryField.FieldId][assetCenterCodeField.FieldId]?.ToString() : item[assetCenterCodeField.FieldId]?.ToString();
                    }

                    var assetName = item["name"] == null ? item[assetQueryField.FieldId]["name"]?.ToString() : item["name"]?.ToString();

                    var assetCenterCode = "";
                    var assetCompanyCode = "";
                    var assetTaxAmount = "";
                    var assetTotalPriceAndTax = "";
                    var assetInvoiceTypeCode = "";
                    var assetTaxCode = "";
                    if (sourceType == 50)
                    {
                        assetCenterCode = centercode;
                        assetTaxAmount = item[taxAmountField.FieldId] == null ? item[assetQueryField.FieldId][taxAmountField.FieldId]?.ToString() : item[taxAmountField.FieldId]?.ToString();
                        assetTotalPriceAndTax = item[totalPriceAndTaxField.FieldId] == null ? item[assetQueryField.FieldId][totalPriceAndTaxField.FieldId]?.ToString() : item[totalPriceAndTaxField.FieldId]?.ToString();
                        assetInvoiceTypeCode = item[invoiceTypeCodeField.FieldId] == null ? item[assetQueryField.FieldId][invoiceTypeCodeField.FieldId]?.ToString() : item[invoiceTypeCodeField.FieldId]?.ToString();
                        assetTaxCode = item[taxCodeField.FieldId] == null ? item[assetQueryField.FieldId][taxCodeField.FieldId]?.ToString() : item[taxCodeField.FieldId]?.ToString();
                    }
                    else if (sourceType == 49)
                    {
                        assetCenterCode = item[centerField.FieldId] == null ? item[assetQueryField.FieldId][centerField.FieldId]["label"]?.ToString() : item[centerField.FieldId]["label"]?.ToString();
                        assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();

                    }
                    else
                    {

                        assetCompanyCode = item[companyCodeField.FieldId] == null ? item[assetQueryField.FieldId][companyCodeField.FieldId]?.ToString() : item[companyCodeField.FieldId]?.ToString();
                        if (string.IsNullOrEmpty(assetCompanyCode) && sourceType == 48)
                        {
                            assetCompanyCode = Data.Data[clearCompanyCode.FieldId]!.ToString();

                        }

                    }
                    pushAssets.Add(new Asset()
                    {

                        Barcode = barcode,
                        Name = assetName,
                        Specs = spec,
                        AssetTypeCode = GetTopAssetTypeCode(assetTypeCode),
                        Amount = amount,
                        ExtraData = new JsonObject
                        {
                            ["FACode"] = FACode,//sap资产编码
                            ["CenterCode"] = assetCenterCode,
                            ["CompanyCode"] = assetCompanyCode,
                            ["TaxAmount"] = assetTaxAmount,
                            ["TotalPriceAndTax"] = assetTotalPriceAndTax,
                            ["InvoiceTypeCode"] = assetInvoiceTypeCode,
                            ["TaxCode"] = assetTaxCode
                        }
                    });
                }
            }
            return pushAssets;
        }
        private bool IsPush(string assetTypeCode)
        {
            string NotPushSap = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "NotPushAssetType").FieldId;
            var code = GetTopAssetTypeCode(assetTypeCode);
            _logger.LogInformation("推送sap资产编码是否推送：" + NotPushSap.Contains("," + code + ","));
            return NotPushSap.Contains("," + code + ",");
        }
        private string GetTopAssetTypeCode(string assetTypeCode)
        {
            List<AssetType> assetTypeList = GetAssetTypeFromCache();
            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchyId = assetType.Hierarchy.Split('|')[0];
            int topAssetTypeId = 0;
            int.TryParse(hierarchyId, out topAssetTypeId);
            var topAssetType = assetTypeList.Where(e => e.Id == topAssetTypeId).FirstOrDefault();
            if (topAssetType != null)
            {
                return topAssetType.Code;
            }
            else
            {
                return assetTypeCode;
            }
        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
    }
}
